﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;

namespace SPMetadataSecurity
{
    [Serializable]
    public class Rule
    {
        private List<Condition> _conditions;
        public string Name { get; set; }

        public int SequenceNumber { get; set; }

        public bool StopIfRuleApplies { get; set; }

        public List<Condition> Conditions 
        {
            get 
            {
                if(_conditions == null)
                {
                    _conditions = new List<Condition>();
                }
                _conditions = _conditions.OrderBy(c => c.Id).ToList();
                return _conditions;
            }
            set
            {
                _conditions = value;
            }
        }
        
        public PermissionAction Action { get; set; }

        public bool AddCondition(Condition condition, out string message)
        {
            bool isSuccess = false;
            try
            {
                message = "Condition added successfully.";
                if (condition != null)
                {
                    if (Conditions == null)
                    {
                        Conditions = new List<Condition>();
                    }
                    Conditions.Add(condition);
                }
            }
            catch (Exception ex)
            {
                message = ex.Message + Environment.NewLine + ex.StackTrace;
            }            
            return isSuccess;
        }

        public bool RemoveCondition(int conditionId, out string message)
        {
            bool isSuccess = false;
            try
            {
                message = "Condition removed successfully.";
                if (conditionId > 0)
                {
                    if (Conditions != null && Conditions.Count > 0)
                    {
                        Conditions.Remove(Conditions.FirstOrDefault(x => x.Id == conditionId));
                    }                   
                }
            }
            catch (Exception ex)
            {
                message = ex.Message + Environment.NewLine + ex.StackTrace;
            }
            return isSuccess;
        }
    }
}
